<template>
	<view class="wrap">
		<view class="dev-area">

			<view class="dev-cart">
				<view class="">
					<view class="dev-name">温度</view>
					<image class="dev-logo" src="../../static/temp.png" mode=""></image>
				</view>
				<view class="dev-data">{{temp}} ℃</view>
			</view>

			<view class="dev-cart">
				<view class="">
					<view class="dev-name">LED灯</view>
					<image class="dev-logo" src="../../static/led.png" mode=""></image>
				</view>
				<switch :checked="led" @change="OnLedSwitch" color="#2b9939" />
			</view>
			
			<view class="dev-cart">
					<view class="dev-name">开发中</view>
			</view>
		</view>
	</view>

</template>

<script>
	const {
		createCommonToken
	} = require('@/key.js')
	export default {
		data() {
			return {
				temp: '0.0',
				led: false,
				token: '',
			}
		},
		onLoad() {
			const params = {
				author_key: 'zI4/BXd+mT+7xjFVjLlJIMaJrNHyR3eReozyWy8MfdJT35Z/bDCINhfsfFyi6E7S',
				version: '2022-05-01',
				user_id: '449198',
			}
			this.token = createCommonToken(params);
		},
		onShow() {
			this.fetchDevData();
			setInterval(()=>{
				this.fetchDevData();
			},1000)
		},
		methods: {
			fetchDevData() {
				uni.request({
					url: 'https://iot-api.heclouds.com/thingmodel/query-device-property',
					method: 'GET',
					data: {
						product_id: '3h7XtWS80P',
						device_name: 'd1'
					},
					header: {
						'authorization': this.token //自定义请求头信息
					},
					success: (res) => {
						console.log(res.data);
						console.log(res.data.data[1].value);
						console.log(res.data.data[0].value);
						this.temp = res.data.data[1].value;
						this.led = res.data.data[0].value === 'true';
					}
				});

			},
			OnLedSwitch(event) {
				console.log(event.detail.value);
				let value = event.detail.value;
				uni.request({
					url: 'https://iot-api.heclouds.com/thingmodel/set-device-property',
					method: 'POST',
					data: {
						product_id: '3h7XtWS80P',
						device_name: 'd1',
						params: {
							"LEDState": value
						}
					},
					header: {
						'authorization': this.token //自定义请求头信息
					},
					success: () => {
						console.log('LEDState ' + (value ? 'ON' : 'OFF') + ' !');
					}
				});
			}

		}
	}
</script>

<style>
  .wrap {
    padding: 30rpx;
  }

  .dev-area {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .dev-cart {
    height: 150rpx;
    width: 300rpx;
    border-radius: 30rpx;
    margin-top: 30rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-shadow: 0 0 15rpx #ccc;
  }

  .dev-name {
    font-size: 35rpx; 
    text-align: center;
    color: #6d6d6d;
  }

  .dev-logo {
    width: 70rpx;
    height: 70rpx;
    margin-top: 10rpx;
  }

  .dev-data {
    font-size: 50rpx; 
    color: #6d6d6d;
  }
</style>